/*
 * @Descripttion: 
 * @version: 
 * @Author: LEO
 * @Date: 2021-05-08 10:14:36
 * @LastEditors: yangzonglong
 * @LastEditTime: 2021-05-17 14:40:23
 */
import React, { useState, useMemo, useCallback, useRef, useEffect } from 'react';
import { PageHeader, Table, Search, Tabs, ActionText, history, units, Button } from '@library';
import { TableRefProps } from '@library/components/table/interface';
import { convertStatus } from './data';
import { WorkFlowHeadProps } from '../../interface';
import { db } from '@library'
import QuerySession from '../../components/querySession/_QuerySession';
const QuerySessionIns = new QuerySession();

//import style from './style.module.scss';

const i18NT = window.$app.t;

const tabs = [
  { label: i18NT('statusNoRelease'), id: '10' },
  { label: i18NT('statusOkRelease'), id: '20' }
];
const woStatus = {
  statusNoRelease: '10',
  statusOkRelease: '20'
};

const ellipsis = true
const tooltip = true;
export const columns = [
  { title: i18NT('workflowName'), dataIndex: 'workflowName', width: 150, ellipsis, tooltip },
  { title: i18NT('formName'), dataIndex: 'formName', width: 150, ellipsis, tooltip },
  { title: i18NT('status'), dataIndex: 'status', width: 100, ellipsis, tooltip },
  { title: i18NT('updatedAt'), dataIndex: 'updatedAt', format: 'time', width: 150, ellipsis, tooltip },
  { title: i18NT('action'), dataIndex: 'action', width: 120, fixed: 'right' },
];

const ModelPage = () => {

  const tableRef = useRef<TableRefProps>(null);
  const searchRef = useRef<any>(null);

  const [keyword, setKeyword] = useState('');
  const [curTab, setCurTab] = useState('10');
  const [pages, setPages] = useState(undefined);
  const [dataSource, setDataSource] = useState<any>([])

  useEffect(() => {
    // query data
    db.getWorkflowsByStatus(curTab).then((list) => {
      console.log('workflows', list)
      setDataSource(list)
    })
  }, [curTab, keyword])

  useEffect(() => {
    if (history._isFromBreadcrumb) {
      const queryObj = QuerySessionIns.getQuerySession();
      if (queryObj) {
        setKeyword(queryObj.fuzzyValue || '');
        setCurTab(queryObj?.where?.status || '10');
        setPages(queryObj?.pages);
        searchRef.current?.setValue(queryObj.fuzzyValue);
      }
      history._isFromBreadcrumb = false;
    }
  }, []);

  const onSearch = useCallback(setKeyword, []);

  const onChangeTab = useCallback((curTabId: string) => {
    setKeyword('');
    setCurTab(curTabId);
  }, []);

  const newBuild = useCallback(() => {
    history.push(`/mymodel/details`);
  }, []);

  const goDetail = useCallback((record: WorkFlowHeadProps) => {
    const query = tableRef.current?.getQuery!();
    console.log(query, 'query');
    QuerySessionIns.setQuerySession(query);
    history.push(`/mymodel/details?id=${record.id}`);
  }, []);

  const deleteLine = useCallback(async (record) => {
    let data = await db.deleteWorkflow(record.id);
    if (data) {
      units.message.success(i18NT('success'));
      setDataSource(dataSource.filter(item => item.id != record.id))
    }
  }, []);

  const withdraw = useCallback(async (record) => {
    let data = await db.withdrawWorkflow(record.id);
    if (data) {
      units.message.success(i18NT('success'));
      setDataSource(dataSource.filter(item => item.id != record.id))
    }
  }, []);

  const rightExtendElement = useMemo(() => {
    return (
      <>
        <Search placeholder={i18NT('inputprocessname')} onSearch={onSearch} ref={searchRef} />
        <Button.Create onClick={newBuild} type='primary'></Button.Create>
      </>
    );
  }, [onSearch, newBuild, curTab]);

  const tableExtra = useMemo(() => {
    const renders = [{
      dataIndex: "status",
      render: (text: string, record: WorkFlowHeadProps, index: number) => <span>{convertStatus(text)}</span>
    }];
    renders.push({
      dataIndex: "action",
      render: (text: string, record: WorkFlowHeadProps, index: number) => <>
        <ActionText.View onClick={() => goDetail(record)} type={i18NT('detail')} />
        {curTab === woStatus['statusNoRelease'] && <ActionText.Delete isModalTip onClick={() => deleteLine(record)} type={i18NT('delete')} />}
        {curTab === woStatus['statusOkRelease'] && <ActionText.OnlyEdit onClick={() => withdraw(record)} type={i18NT('withdraw')} />}
      </>
    }
    );
    return renders;
  }, [goDetail, deleteLine, withdraw, curTab]);

  return (
    <>
      <PageHeader />
      <div className='common-block-table'>
        <PageHeader title={<Tabs onChange={onChangeTab} curTabId={curTab} tabs={tabs} mode="tabs" />}
          extra={rightExtendElement} />
        <div className='common-white-space'></div>
        <Table ref={tableRef} extra={tableExtra} columns={columns} dataSource={dataSource} recordSort='ModelList' />
      </div>
    </>
  );
};

export default ModelPage